package cc.mrbird.web.service.impl;

import cc.mrbird.common.service.impl.BaseService;
import cc.mrbird.system.domain.OneStudent;
import cc.mrbird.web.dao.OneStudentMapper;
import cc.mrbird.web.dao.StudentMapper;
import cc.mrbird.web.domain.RespImport;
import cc.mrbird.web.hanlder.OneStudentExcelHandler;
import cc.mrbird.web.service.OneStudentService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Service("oneStudentService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class OneStudentServiceImpl extends BaseService<OneStudent> implements OneStudentService {

    private static final Logger log = LoggerFactory.getLogger(OneStudentServiceImpl.class);

    @Autowired
    private OneStudentMapper oneStudentMapper;

    @Override
    public void addOneStudent(OneStudent oneStudent,String oneUserName) {
        oneStudent.setCreatedTime(new Date());
        oneStudent.setUpdatedTime(new Date());
        oneStudent.setUserName(oneUserName);
        oneStudentMapper.insertOneStudent(oneStudent);
        log.info("插入学生信息成功");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void updateOneStudent(OneStudent oneStudent) {

        oneStudent.setUpdatedTime(new Date());
        oneStudentMapper.updateOneStudent(oneStudent);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void deleteOneStudents(String studentIds) {

        List<String> list = Arrays.asList(studentIds.split(","));
        oneStudentMapper.deleteByIds(list);
    }

    @Override
    public RespImport ImportOneStudent(MultipartFile file, String userName) {

        ImportParams importParams = new ImportParams();      // 数据处理
        IExcelDataHandler<OneStudent> handler = new OneStudentExcelHandler();
        handler.setNeedHandlerFields(new String[] { "考生号" });// 注意这里对应的是excel的列名。也就是对象上指定的列名。
        importParams.setDataHanlder(handler);

        // 需要验证
        importParams.setNeedVerfiy(true);

        List<OneStudent> successList = null;
        List<OneStudent> failList = null;
        int successNum = 0,failureNum =0,repeatNum = 0;
        RespImport respImport = new RespImport();
        String tempRepeatStudentId = null;
        String tempFailureStudentId = null;
        String tempRepeatIDNumber = null;
        String tempFailureIDNumber = null;
        try {
            ExcelImportResult<OneStudent> result = ExcelImportUtil.importExcelMore(file.getInputStream(), OneStudent.class,
                    importParams);

            successList = result.getList();
            failList = result.getFailList();

            log.info("是否存在验证未通过的数据:" + result.isVerfiyFail());
            log.info("验证通过的数量:" + successList.size());
            log.info("验证未通过的数量:" + failList.size());

        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        for ( OneStudent oneStudent : successList) {
            oneStudent.setUserName(userName);
            oneStudent.setCreatedTime(new Date());
            oneStudent.setUpdatedTime(new Date());
            OneStudent resultId = oneStudentMapper.findById(oneStudent.getOneStudentId());
            OneStudent resultIdNum = oneStudentMapper.findByIdNumber(oneStudent.getIdNumber());
            if (resultId != null){
                repeatNum++;
                failureNum++;
                tempRepeatStudentId += resultId.getOneStudentId()+"、";
                tempRepeatStudentId = tempRepeatStudentId.replace("null","");
                respImport.setRepeatStudentId(tempRepeatStudentId);
                log.info("考生号已存在:" + resultId.getOneStudentId() );
            }
            if (resultIdNum != null){
                repeatNum++;
                failureNum++;
                tempRepeatIDNumber += resultIdNum.getIdNumber()+"、";
                tempRepeatIDNumber = tempRepeatIDNumber.replace("null","");
                respImport.setRepeatIDNumber(tempRepeatIDNumber);
                log.info("身份证号："+resultIdNum.getIdNumber()+"已存在" );
            }
            if (resultId == null && resultIdNum == null){
                successNum++;
                oneStudentMapper.insertOneStudent(oneStudent);
            }
            log.info("插入学生信息成功");
            log.info("成功列表信息:ID=" + oneStudent.getOneStudentId() + oneStudent.getName() );
        }
        for (OneStudent oneStudent : failList) {
            tempFailureStudentId += oneStudent.getOneStudentId()+"、";
            tempFailureStudentId = tempFailureStudentId.replace("null","");
            respImport.setFailureStudentId(tempFailureStudentId);
            tempFailureIDNumber += oneStudent.getIdNumber()+"、";
            tempFailureIDNumber = tempFailureIDNumber.replace("null","");
            respImport.setFailureIDNumber(tempFailureIDNumber);
            //log.info("失败信息:" + oneStudent.getOneStudentId() + oneStudent.getName() );
            failureNum++;
        }
        respImport.setSuccessNum(successNum);
        respImport.setFailureNum(failureNum);
        return respImport;
    }

    @Override
    public List<OneStudent> findOneStudentAll() {
        return oneStudentMapper.findOneStudentAll();
    }

    @Override
    public List<OneStudent> findOneStudentByCondition(OneStudent oneStudent) {
        return oneStudentMapper.findOneStudentByCondition(oneStudent);
    }

    /**
     * 根据id查找考生信息
     * @param studentId
     * @return
     */
    @Override
    public OneStudent findById(String studentId) {
        return oneStudentMapper.findById(studentId);
    }

    /**
     * 根据id查找考生信息
     * @param idNumber
     * @return
     */
    @Override
    public OneStudent findByIdNumber(String idNumber) {
        return oneStudentMapper.findByIdNumber(idNumber);
    }

}
